<template>
  <div class="bg-white my-[10px]">
    <BaseHead>预算明细（单位：万元）</BaseHead>
    <div class="px-[100px] py-[10px] flex">
      <div>预算页扫描件</div>
      <div class="felx-1 ml-[10px]">
        <FileUpload :uploadUrl="uploadUrl" v-model="fileList" @change="fileChange(row)" />
      </div>
    </div>
    <el-table
      :data="budgetList"
      class="w-full"
      border
      stripe
      row-key="id"
      default-expand-all
      :tree-props="{ hasChildren: 'hasChild' }"
      show-summary
      :summary-method="summaryFn"
    >
      <el-table-column type="index" label="序号" width="60px" />
      <el-table-column prop="name" label="预算科目" />
      <el-table-column prop="feeRatio" label="经费占比">
        <template #default="{ row }">
          {{ (row.feeRatio ? row.feeRatio : 0) + "%" }}
        </template></el-table-column
      >
      <el-table-column prop="lxMoney" label="预算经费">
        <template #default="{ row }">
          <div v-if="row.children.length">{{ row.lxMoney }}</div>
          <el-input v-model="row.lxMoney" clearable @input="valueChange(row, $event)" v-else />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import FileUpload from "@/views/project/components/FileUpload.vue";
import { budgetDetail, editBudget } from "@/api/project/zx/lxxm";
import { fomateNumber, fiexdNumber } from "@/utils/main";
import { ElMessage } from "element-plus";
const uploadUrl = `/commonFile/uploadFile?modelName=校级项目立项预算扫描件`;
const operateId = ref(null);
const budgetList = ref([]);
const totalFee = ref(0); //总经费
const fileList = ref([]); //文件集合
let fileIds = ""; //文件id
const isAuditor = inject("isAuditor");
const taskId = inject("taskId");
const checkStatus = inject("checkStatus");
//获取预算信息详情
const getBudgetDetail = async () => {
  const params = {
    proId: operateId.value,
  };
  try {
    const res = await budgetDetail(params);
    budgetList.value = res.data.bizProjectBudgetFeeList || [];
    //金额字符串类型转数字类型 feeRatio为null时 设默认值0
    const moneyToNumber = (rows) => {
      for (let i = 0; i < rows.length; i++) {
        rows[i].lxMoney = rows[i].lxMoney ? parseFloat(rows[i].lxMoney) : 0;
        rows[i].feeRatio = rows[i].feeRatio ? parseFloat(rows[i].feeRatio) : 0;
        if (rows[i].children) {
          moneyToNumber(rows[i].children);
        }
      }
    };
    moneyToNumber(budgetList.value);
    totalFee.value = parseFloat(res.data.proInitOtherBaseInfoVo.feeAuthorize);
    const fileArray = res.data.proInitOtherBaseInfoVo.fileInfos || [];
    fileArray.forEach((item) => {
      fileList.value.push({
        id: item.fileId,
        name: item.fileName,
      });
    });
  } catch (error) {
    console.log(error);
  }
};
//编辑
const edit = async (id) => {
  operateId.value = id;
  //获取成员列表
  getBudgetDetail();
};
//输入的预算经费改变
const valueChange = (row, val) => {
  fomateNumber(row, "lxMoney", val);
  if (!row.lxMoney) {
    row.lxMoney = 0;
  }
  nextTick(() => {
    row.feeRatio = Math.round((parseFloat(row.lxMoney) / totalFee.value) * 10000) / 100;
    const updateParentMoney = (nodes) => {
      return nodes.map((node) => {
        // 如果有子节点，则递归处理子节点
        if (node.children && node.children.length > 0) {
          const updatedChildren = updateParentMoney(node.children);
          const sumFee = updatedChildren.reduce((acc, cur) => {
            return acc + (cur.lxMoney ? parseFloat(cur.lxMoney) : 0);
          }, 0);
          const sumFeeRatio = updatedChildren.reduce((acc, cur) => {
            return acc + (cur.feeRatio ? parseFloat(cur.feeRatio) : 0);
          }, 0);
          return {
            ...node,
            lxMoney: fiexdNumber(sumFee, 6),
            feeRatio: fiexdNumber(sumFeeRatio),
            children: updatedChildren,
          };
        }
        // 没有子节点则直接返回
        return node;
      });
    };
    budgetList.value = updateParentMoney(budgetList.value);
  });
};
//合计方法
const summaryFn = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    if (index == 0) {
      sums[index] = "";
    } else if (index == 1) {
      sums[index] = "合计";
    } else {
      let total = 0;
      data.forEach((item) => {
        total += parseFloat(item[column.property]);
      });
      if (index == 2) {
        sums[index] = fiexdNumber(total) + "%";
      } else {
        sums[index] = fiexdNumber(total, 6);
        //如果输入的经费合计等于总经费 则经费占比置为100 防止出现100.1% 这类情况
        if (fiexdNumber(total, 6) == totalFee.value) {
          sums[index - 1] = "100%";
        }
      }
    }
  });
  return sums;
};
const emit = defineEmits(["save-success", "save-ok"]);
//保存
const save = async (submitType) => {
  try {
    //判断预算信息是否为空
    if (!budgetList.value.length) {
      ElMessage({
        message: "请填写预算信息！",
        type: "error",
      });
      return;
    }
    //判断填写的预算总经费是否与项目总经费相等
    let total = 0;
    budgetList.value.forEach((item) => {
      total += parseFloat(item.lxMoney);
    });
    //判断预算经费合计是否与总经费相等
    if (fiexdNumber(total, 6) != totalFee.value) {
      ElMessage({
        message: "预算经费合计与总预算经费不相等！",
        type: "error",
      });
      return;
    }
    const bizProjectBudgetFee = [];
    const getParams = (rows) => {
      for (let i = 0; i < rows.length; i++) {
        bizProjectBudgetFee.push({
          budgetStandardId: rows[i].standardId,
          budgetType: "liuxiao",
          feeRatio: rows[i].feeRatio,
          subjectCode: rows[i].code,
          subjectId: rows[i].id,
          subjectFee: rows[i].lxMoney,
          projectId: operateId.value,
        });
        if (rows[i].children) {
          getParams(rows[i].children);
        }
      }
    };
    getParams(budgetList.value);
    let params = {
      bizProjectBudgetBatch: {
        budgetFee: totalFee.value, //预算总金额
        budgetFileId: fileIds, //预算页扫描件ID
        budgetStandardId: bizProjectBudgetFee[0].budgetStandardId,
        projectClass: "xJProject",
        projectId: operateId.value, //项目id
        submitType,
        isAuditor: isAuditor.value,
        taskId: taskId.value,
        checkstatus: checkStatus.value,
      },
      bizProjectBudgetFee,
    };
    const res = await editBudget(params);
    if (res.code === 200) {
      emit("save-success");
    }
  } catch (error) {
    console.log(error);
  } finally {
    emit("save-ok");
  }
};
defineExpose({ edit, save });
//上传附件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  fileIds = ids.join(",");
};
</script>

<style scoped lang="scss"></style>
